const Koa = require("koa");
const app = new Koa();
const json = require("koa-json");
const parameter = require("koa-parameter");
const cors = require("koa-cors");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const sessionMiddleware = require("./middlewares/session.middleware");
const responseHandler = require("./middlewares/responseHandler.middleware");
const checkLogin = require("./middlewares/checkLogin.middleware");
const users = require("./routes/users");
const {
  loggerMiddleware,
  logger,
} = require("../src/middlewares/logger.middleware"); // 引入上一步中配置的logger
//设置全局token失效列表
global.blackTokenList = [];
// 错误处理
onerror(app);
// 解析请求体
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(json());
//参数校验中间件
app.use(parameter(app));
//处理跨域问题中间件
app.use(cors());
//处理静态资源
app.use(require("koa-static")(__dirname + "/public"));
// 日志
app.use(loggerMiddleware);
app.use(async (ctx, next) => {
  ctx.logger = logger;
  await next();
});
//处理错误状态
app.use(responseHandler);
//登录验证
app.use(checkLogin);
//处理session
app.use(sessionMiddleware(app));
// 处理路由中间件
app.use(users.routes(), users.allowedMethods());

// 错误处理
app.on("error", (err, ctx) => {
  ctx.logger.error("server error", err, ctx);
});

module.exports = app;
